/*
 * Copyright (C) 2011 Sony Ericsson Mobile Communications AB.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.sonyericsson.example;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;

public class ExampleExtensionActivity extends Activity {

	private long mAlbumId;
    private StringBuilder sFormatBuilder = new StringBuilder();
    private Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
    private final Object[] sTimeArgs = new Object[5];

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setTitle(R.string.description);

        // Retrieve the URI from the intent, this is a URI to a MediaStore audio
        // file
        Intent intent = getIntent();
        Uri trackUri = intent.getData();
        
        // Define the columns we want to retrieve for the audio file
        // Note ALBUM_ART column is not present
		final String[] cols = new String[] { 
					MediaStore.Audio.Media._ID,
					MediaStore.Audio.Media.TITLE,
					MediaStore.Audio.Media.ARTIST,
					MediaStore.Audio.Media.ALBUM,
					MediaStore.Audio.Media.DATE_ADDED,
					MediaStore.Audio.Media.DATE_MODIFIED,
					MediaStore.Audio.Media.SIZE,
					MediaStore.Audio.Media.DATA,
                    MediaStore.Audio.Media.DISPLAY_NAME,
                    MediaStore.Audio.Media.DURATION,
                    MediaStore.Audio.Media.ALBUM_ID
			      	};
        

        // Use it to query the media provider
        Cursor trackCursor = getContentResolver().query(
                trackUri,
                cols, null, null, null);

        if (trackCursor != null) {
            try {
                if (trackCursor.moveToFirst()) {

                	
                	// And retrieve the wanted information
        			String idStr = trackCursor.getString(trackCursor
        					.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));        			
                    String trackName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    String artistName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    String albumName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
        			long datems = 1000 * trackCursor.getLong(trackCursor
        					.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED));
        			String dateAdded = android.text.format.DateFormat.format("dd/MM/yyyy hh:mm", datems).toString();        			
        			long datemodms = 1000 * trackCursor.getLong(trackCursor
        					.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED));
        			String dateModified =  android.text.format.DateFormat.format("dd/MM/yyyy hh:mm", datemodms).toString();
                    long size = trackCursor.getLong(trackCursor
                    		.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                    String sizeStr = makeSizeString(size);
                    String location = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    String displayName = trackCursor.getString(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                    
                    //ms eg 284194 is actually 4mins and a bit...
                    long duration = trackCursor.getLong(trackCursor
                            .getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));                    
                    String durationStr = makeTimeString(this, duration);

                    ((TextView)findViewById(R.id.audioId)).setText(idStr);
                    ((TextView)findViewById(R.id.track)).setText(trackName);
                    ((TextView)findViewById(R.id.album)).setText(albumName);
                    ((TextView)findViewById(R.id.artist)).setText(artistName);
                    ((TextView)findViewById(R.id.dateAdded)).setText(dateAdded);
                    ((TextView)findViewById(R.id.dateModified)).setText(dateModified);
                    ((TextView)findViewById(R.id.size)).setText(sizeStr);
                    ((TextView)findViewById(R.id.location)).setText(location);
                    ((TextView)findViewById(R.id.displayName)).setText(displayName);
                    ((TextView)findViewById(R.id.duration)).setText(durationStr);
                    
                    //Store until the view has been layed out, as view.width and height
                    //return 0 in onCreate
                    mAlbumId = trackCursor.getLong(trackCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                }
            }
            finally {
                trackCursor.close();
            }
        }

    }
	
	/**
	 * Note we cannot do this in OnCreate as the view has not yet been rendered,
	 * so view width and height would return 0.
	 */
    @Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		
        Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart"); 
        Uri uri = ContentUris.withAppendedId(sArtworkUri, mAlbumId); 
        
		InputStream in = null;
		try {
			in = getContentResolver().openInputStream(uri);
		} catch (FileNotFoundException e) {
			return;
		}
		
		Bitmap artwork = BitmapFactory.decodeStream(in); 
		View v = findViewById(R.id.nowplayingparent);
		
		setBackground(v, artwork);
	}
    
    private String makeSizeString(long sizeBytes) {
		long kb = sizeBytes / 1024;
		if (kb == 0) {
			return String.valueOf(sizeBytes) + " bytes";
		} else {
			float mb = kb / 1024;
			if(mb < 1.0) {
				return String.valueOf(kb) + " Kb";
			} else {
				float gb = mb / 1024;
				if(gb < 1.0) {
					return String.valueOf(mb) + " Mb";
				} else {			
					NumberFormat numberFormat = DecimalFormat.getInstance();
					numberFormat.setMaximumFractionDigits(2);
					String formattedText = numberFormat.format(gb);
					return formattedText + " Gb";
				}
			}
		}
    }
    
    private String makeTimeString(Context context, long ms) {
    	long secs = ms / 1000;
        String durationformat = context.getString(
                secs < 3600 ? R.string.durationformatshort : R.string.durationformatlong);
        
        /* Provide multiple arguments so the format can be changed easily
         * by modifying the xml.
         */
        sFormatBuilder.setLength(0);

        final Object[] timeArgs = sTimeArgs;
        timeArgs[0] = secs / 3600;
        timeArgs[1] = secs / 60;
        timeArgs[2] = (secs / 60) % 60;
        timeArgs[3] = secs;
        timeArgs[4] = secs % 60;

        return sFormatter.format(durationformat, timeArgs).toString();
    }
    
    private void setBackground(View v, Bitmap bm) {
    	
        if (bm == null) {
            v.setBackgroundResource(0);
            return;
        }

        int vwidth = v.getWidth();
        int vheight = v.getHeight();
        int bwidth = bm.getWidth();
        int bheight = bm.getHeight();
        float scalex = (float) vwidth / bwidth;
        float scaley = (float) vheight / bheight;
        float scale = Math.max(scalex, scaley) * 1.3f;
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        Bitmap bg = Bitmap.createBitmap(vwidth, vheight, config);        
        Canvas c = new Canvas(bg);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        ColorMatrix greymatrix = new ColorMatrix();
        greymatrix.setSaturation(0);
        ColorMatrix darkmatrix = new ColorMatrix();
        darkmatrix.setScale(.3f, .3f, .3f, 1.0f);
        greymatrix.postConcat(darkmatrix);
        ColorFilter filter = new ColorMatrixColorFilter(greymatrix);
        paint.setColorFilter(filter);
        Matrix matrix = new Matrix();
        matrix.setTranslate(-bwidth/2, -bheight/2); // move bitmap center to origin
        matrix.postRotate(10);
        matrix.postScale(scale, scale);
        matrix.postTranslate(vwidth/2, vheight/2);  // Move bitmap center to view center      
        c.drawBitmap(bm, matrix, paint);
        v.setBackgroundDrawable(new BitmapDrawable(bg));
    }
    
    
}
